<template>
  <div class="cropperContent" @click="editCropper()">
    <img v-if="options.img" :src="options.img" class="cropperContent-img" />
    <img
      v-else
      src="@/assets/images/layout/avatar.png"
      class="_upload"
      alt=""
    />
    <el-dialog
      title="上传图片"
      v-model="open"
      width="800px"
      append-to-body
      @opened="modalOpened"
      @close="closeDialog"
    >
      <el-row>
        <el-col :xs="24" :md="12" :style="{ height: '350px' }">
          <vue-cropper
            v-if="visible"
            ref="cropper"
            :img="options.img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            :outputType="options.outputType"
            @realTime="realTime"
          />
        </el-col>
        <el-col :xs="24" :md="12" :style="{ height: '350px' }">
          <div class="cropperContent-preview">
            <img :src="options.previews.url" :style="options.previews.img" />
          </div>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :lg="2" :md="2">
          <el-upload
            action="#"
            :http-request="requestUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <el-button>
              选择
              <el-icon class="el-icon--right"><Upload /></el-icon>
            </el-button>
          </el-upload>
        </el-col>
        <el-col :lg="{ span: 1, offset: 2 }" :md="2">
          <el-button icon="Plus" @click="changeScale(1)"></el-button>
        </el-col>
        <el-col :lg="{ span: 1, offset: 1 }" :md="2">
          <el-button icon="Minus" @click="changeScale(-1)"></el-button>
        </el-col>
        <el-col :lg="{ span: 1, offset: 1 }" :md="2">
          <el-button icon="RefreshLeft" @click="rotateLeft()"></el-button>
        </el-col>
        <el-col :lg="{ span: 1, offset: 1 }" :md="2">
          <el-button icon="RefreshRight" @click="rotateRight()"></el-button>
        </el-col>
        <el-col :lg="{ span: 2, offset: 7 }" :md="2">
          <el-button type="primary" @click="uploadImg()">提 交</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup>
import "vue-cropper/dist/index.css";
import { VueCropper } from "vue-cropper";
import { upload } from "@/api/common";

const props = defineProps({
  coverImage: {
    type: String,
    default: "",
  },
  autoCrop: {
    type: Boolean,
    default: true,
  },
  autoCropWidth: {
    type: Number,
    default: 200,
  },
  autoCropHeight: {
    type: Number,
    default: 200,
  },
  outputType: {
    type: String,
    default: "png",
  }
});
const { coverImage } = toRefs(props);

// watch(
//   () => props.coverImage,
//   (newVal, oldVal) => {
//     if (newVal) {
//       options.img = newVal;
//     }
//   }
// );

const { proxy } = getCurrentInstance();

const open = ref(false);
const visible = ref(false);

//图片裁剪数据
const options = reactive({
  img: props.coverImage,
  autoCrop: props.autoCrop, // 是否默认生成截图框
  autoCropWidth: props.autoCropWidth, // 默认生成截图框宽度
  autoCropHeight: props.autoCropHeight, // 默认生成截图框高度
  fixedBox: true, // 固定截图框大小 不允许改变
  outputType: props.outputType, // 默认生成截图为PNG格式
  previews: {}, //预览数据
});

/** 编辑头像 */
const editCropper = () => {
  open.value = true;
};
/** 打开弹出层结束时的回调 */
const modalOpened = () => {
  visible.value = true;
};
/** 覆盖默认上传行为 */
const requestUpload = () => {};
/** 向左旋转 */
const rotateLeft = () => {
  proxy.$refs.cropper.rotateLeft();
};
/** 向右旋转 */
const rotateRight = () => {
  proxy.$refs.cropper.rotateRight();
};
/** 图片缩放 */
const changeScale = (num) => {
  num = num || 1;
  proxy.$refs.cropper.changeScale(num);
};
/** 上传预处理 */
const beforeUpload = (file) => {
  if (file.type.indexOf("image/") == -1) {
    proxy.$modal.msgError(
      "文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。"
    );
  } else {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      options.img = reader.result;
    };
  }
};
/** 上传图片 */
const uploadImg = () => {
  if(!proxy.$refs.cropper.img){
    proxy.$modal.msgError(
      "请选择上传图片"
    );
    return
  }

  proxy.$refs.cropper.getCropBlob((data) => {
    let formData = new FormData();
    formData.append("file", data);
    upload(formData).then((res) => {
      let data = res.data;
      open.value = false;
      emit("update:coverImage", data.url);
      emit("uploadEnd");
      visible.value = false;
    });
  });
};

const emit = defineEmits(["update:coverImage", "uploadEnd"]);

/** 实时预览 */
const realTime = (data) => {
  options.previews = data;
};

/** 关闭窗口 */
const closeDialog = () => {
  options.visible = false;
};
</script>

<style lang='scss' scoped>
.cropperContent {
  cursor: pointer;
  // height: 100px;
  // position: relative;
  // display: inline-block;
  // text-align: center;

  // &:hover:after {
  //   content: "+";
  //   position: absolute;
  //   top: 0;
  //   left: 0;
  //   right: 0;
  //   bottom: 0;
  //   color: #eee;
  //   font-size: 50px;
  //   cursor: pointer;
  //   line-height: 100px;
  //   border-radius: 50%;
  // }

  &-img {
    width: 140px;
    height: 100px;
  }

  &-preview {
    position: absolute;
    top: 50%;
    transform: translate(50%, -50%);
    width: 200px;
    height: 200px;
    box-shadow: 0 0 4px #ccc;
    overflow: hidden;
  }
}

._upload {
  width: 82px;
  height: 82px;
}
</style>